import {Injectable} from '@angular/core';
import {TpHttpService} from './tp-http.service';
import {Site} from '../entity/site';
import {Observable} from 'rxjs/index';
import {tap} from 'rxjs/operators';
import {TpStorageService} from './tp-storage.service';

@Injectable({
    providedIn: 'root'
})
export class SiteService {

    private site: Site;

    constructor(private tpStorageService: TpStorageService,
                private tpHttpService: TpHttpService) {
    }

    get(): Observable<Site> {
        if (this.site) {
            return new Observable<Site>(observer => observer.next(this.site));
        }
        this.site = this.tpStorageService.getObj(TpStorageService.KEY_SITE);
        if (this.site) {
            return new Observable<Site>(observer => observer.next(this.site));
        }
        return this.tpHttpService.get('/api/site')
            .pipe(
                tap((data: Site) => {
                    this.site = data;
                    this.tpStorageService.set(TpStorageService.KEY_SITE, JSON.stringify(data));
                })
            );
    }
}
